package com.market.interceptor;

import com.market.entity.User;
import com.market.utils.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 登录检测拦截器，确保只有登录用户才能访问受保护的API
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    
    // 定义不需要拦截的路径列表
    private static final List<String> EXCLUDED_PATHS = Arrays.asList("/user/login");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        logger.info("LoginInterceptor处理请求: {} {}", method, requestURI);
        
        // 不拦截OPTIONS预检请求
        if ("OPTIONS".equalsIgnoreCase(method)) {
            logger.info("OPTIONS预检请求，直接放行");
            return true;
        }
        
        // 检查请求路径是否在排除列表中
        for (String path : EXCLUDED_PATHS) {
            if (requestURI.contains(path)) {
                logger.info("请求路径在排除列表中，不拦截: {}", requestURI);
                return true;
            }
        }
        
        // 检查用户是否登录
        try {
            User user = (User) request.getSession().getAttribute(SessionUtil.USER_SESSION);
            if (user != null) {
                logger.info("用户已登录: {} (ID={}), 放行请求", user.getUserName(), user.getId());
                return true;
            }
            
            // 未登录，返回错误信息
            logger.warn("用户未登录，拦截请求: {}", requestURI);
            responseError(response);
            return false;
        } catch (Exception e) {
            logger.error("检查用户登录状态时出错", e);
            responseError(response);
            return false;
        }
    }
    
    private void responseError(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 Unauthorized
        response.getWriter().write("{\"flag\":false,\"message\":\"用户未登录或登录已过期\",\"code\":401}");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理完成后的操作
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后的操作
    }
} 